package com.biglead.demo.controller;

import com.biglead.demo.pojo.UserInfo;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api(tags="Redis 测试使用")
@RestController()
@RequestMapping("/redis")
@Slf4j
public class RedisController {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("/testString")
    public String testString()  {
        log.info("redis 开始保存值  ");
        stringRedisTemplate.opsForValue().set("name", "早起的年轻人");
        log.info("redis 保存完成  ");
        String name = stringRedisTemplate.opsForValue().get("name");
        return "redis 中取出的值是  " + name ;
    }

    @GetMapping("/getUser")
    public String testGetUser()  {
        ValueOperations<String, UserInfo> operations = redisTemplate.opsForValue();
        UserInfo userInfo = operations.get("sys.user");
        if(userInfo==null){
            return "未查询到用户";
        }
        return userInfo.toString();
    }
    @GetMapping("/saveUser")
    public String testSaveUser()  {

        UserInfo user = new UserInfo();
        user.setUserName("早起的年轻人");
        user.setUserAge(30);

        ValueOperations<String, UserInfo> operations = redisTemplate.opsForValue();

        //保存数据
        operations.set("sys.user", user);
        // 设置10秒后过期
        operations.set("sys.user", user, 10, TimeUnit.SECONDS);


        return "保存用户信息成功";
    }


    @GetMapping("/get/cache/User")
    @Cacheable(value="user-key")
    public UserInfo getUser() {

        log.info("执行数据库查询用户");
        UserInfo user = new UserInfo();
        user.setUserName("早起的年轻人");
        user.setUserAge(30);

        return user;
    }
}
